/*
ZendUploadify v1.0
Release Date: 2011-08-02

Copyright (c) 2011 Tomasz Ulanowski

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

(function($) {
	$.fn.zendUploadify = function(options) {
		
		if (!swfobject.hasFlashPlayerVersion("9.0.24")) {
			// if no flash bail out...
			return;
		}
		
		var settings = {
			'auto'				: true,
			'script'			: '/uploadify/upload',
			'multi'				: false,
			'returnValueMode'	: 'checkbox', // checkbox|hidden|none,
			
			'preview'			: true,
			'previewContainer'	: null,
			'previewUrl'		: '/uploadify/preview/width/200/height/200/file/%s',
			
			'onComplete'		: onCompleteHandler,
			//'onError'			: onErrorHandler,
			
			'uploader'			: '/lib/uploadify/uploadify.swf',
			'expressInstall'	: '/lib/swfupload/expressInstall.swf',
			'cancelImg'			: '/lib/uploadify/cancel.png',
		};
		
		// merge options
		if (options) {
			$.extend(settings, options);
		}
		
		var elementsCounter = 0;
		return this.each(function() {
			
			// disable input type=file element
			this.disabled = 'disabled';
			
			if (elementsCounter == 0) {
				// setup uploadify only for first element
				$(this).uploadify(settings);
				
				// prepare container for uploaded files
				var uploaderQueue = $('#' + this.id + 'Queue');
				var uploaderFiles = $('<div id="'+this.id+'Files" class="zendUploadifyFiles"></div>');
				uploaderQueue.after(uploaderFiles);
				
			} else {
				// all other elements just hide
				$(this).hide();
			}
			
			elementsCounter++;
		});

		function onCompleteHandler(event, ID, fileObj, response, data) {
			console.log("onComplete", event, ID, fileObj, response, data);
			response = JSON.parse(response);
			if (response.errors) {
				$(response.errors).each(function(key, value){
					for (var k in value) {
						alert(value[k]);
					}					
				});
			}
			else {
				var input = $(event.target);
				var uploaderFiles = $('#' + event.target.id + 'Files');

				$(response.uploaded).each(function(key, file) {
					if (!settings.multi) {
						uploaderFiles.empty();
					}
					
					// generate uploaded file row
					var resultHtml = $('<div class="zendUploadifyFile"></div>'); 
					
					// add input element
					switch (settings.returnValueMode) {
						case 'checkbox':
							resultHtml.append('<label><input type="checkbox" checked="checked" name="' + input.attr('name') + '" value="'+ file.name +'" />' + file.origName + ' (' + file.type+ ' '+ file.sizeHuman + ')</label>');
							break;
						case 'hidden':
							resultHtml.append('<input type="hidden" name="'+ input.attr('name') +'" value="'+ file.name +'" />');
							break;
						default:
							returnInput = false;
					}
					
					// add img preview
					if (settings.preview && file.isImage) {
						var preview = '<div><img src="'+settings.previewUrl.replace('%s', file.name)+'" /></div>';
						console.log(settings.previewContainer);
						if (settings.previewContainer != null) {
							if ( settings.multi ) {
								$(settings.previewContainer).append(preview);
							} else {
								$(settings.previewContainer).html(preview);
							}
						}
						else {
							resultHtml.append(preview);
						}
					}
					
					uploaderFiles.append(resultHtml);
				});
			}						
		}
		
		function onErrorHandler(event, ID, fileObj, errorObj) {
			console.log("onError", event, ID, fileObj, errorObj);
		}
		
	};
})(jQuery);